package com.qf.service.impl;


import com.qf.dao.BooksBorrowDao;
import com.qf.dao.UserDao;
import com.qf.dao.impl.BooksBorrowDaoImpl;
import com.qf.dao.impl.UserDaoImpl;
import com.qf.entity.*;
import com.qf.service.BooksBorrowService;

import java.sql.SQLException;
import java.time.LocalDateTime;

public class BooksBorrowServiceImpl implements BooksBorrowService {
    private BooksBorrowDao booksBorrowDao = new BooksBorrowDaoImpl();
    private UserDao userDao = new UserDaoImpl();
    private Rules rules = null;
    private BooksBorrow booksBorrow = null;
    @Override
    public int addBooksBorrow(Integer uid,Integer bid) {
        try {
            int num1 = -1;
            //先根据uid获取借书对象，查看是否有借书卡，有才能借
            BorrowCard borrowCard = booksBorrowDao.selectBorrowCardByUid(uid);
            if(borrowCard==null){
                //没有权限
                return -2;
            }
            //根据borrow_card借书卡查询对应的rules对象
            rules = booksBorrowDao.selectRulesById(borrowCard.getRule_id());
            //如果不为空则获取书籍对象，判断要借的书是否为state是否为1（是否可借）
            Books books = booksBorrowDao.selectBooksById(bid);
            if(rules==null || books==null){
                return 0;
            }
            if(books.getState()==1){
                User user = userDao.selectUserById(uid);
                if(user!=null){
                    //则可以外借
                    booksBorrow = new BooksBorrow();
                    booksBorrow.setBook_id(bid);
                    booksBorrow.setCard_id(borrowCard.getBcid());
                    booksBorrow.setUser_id(user.getUsername());
                    booksBorrow.setBorrow_date(LocalDateTime.now());
                    booksBorrow.setEnd_date(LocalDateTime.now().plusDays(rules.getLimit_day()));
                    int num = booksBorrowDao.addBooksBorrow(booksBorrow);
                    if(num>0){
                        num1 = booksBorrowDao.updateBooksStatus(bid);
                    }
                }
            }else {
                //表示书已经外借了
                return -1;
            }
            //添加异常
            return num1>0?num1:0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
